from typing import Dict

from django.shortcuts import render, redirect

# Create your views here.
# 创建cookie
from app01 import models
from app01.service import UserService




# 返回登录页面
def fun_login_page(request):
    return render(request,'login.html')

# 实现登录功能
def fun_login(request):
    # 获取表单提交数据
    v_post_data:Dict=request.POST
    v_bb=v_post_data.get('bb',None)
    v_password=v_post_data.get('password',None)
    print(v_bb,v_password)
    # 查找数据库是否存在该数据
    v_result=UserService.finduserbynameandpassword(v_bb,v_password)
    # 如果存在则登录成功，如果不存在，则登录失败
    if v_result>=1:   # 表示登录成功
        return redirect('/login_sucess_page')
    else:             # 表示登录失败
        return redirect('/login_page')


# 登录成功跳转的页面
def fun_login_sucess_page(request):
    return render(request,'html01_success.html')


def fun_login_fail_page(request):
    return render(request, 'html01_fail.html')



#注册如下
# 返回注册页面
def fun_register_page(request):
    return render(request, 'register.html')

def fun_register(request):
    # 定义一个错误提示为空
    error_name = ''
    if request.method=='POST':
        stu = request.POST.get('stuid')
        pas = request.POST.get('user_password')
        name = request.POST.get('stuname')
        se= request.POST.get('sex')
        birth = request.POST.get('birthdate')
        nat = request.POST.get('native')
        entrance = request.POST.get('entrancetime')
        politic= request.POST.get('politicalface')
        add = request.POST.get('address')
        per = request.POST.get('perphone')


        user_list = models.TStudent.objects.filter(stuid=stu)
        if user_list :
            # 注册失败

            error_name = '%s用户名已经存在了' % stu
            # 返回到注册页面，并且把错误信息报出来
            return  render(request,'register.html',{'error_name':error_name})
        else:
             # 数据保存在数据库中，并返回到注册成功页面
             user = models.TStudent.objects.create(stuid=stu,user_password=pas,stuname=name,sex=se,
             birthdate=birth,native=nat,entrancetime=entrance, politicalface=politic,
             address=add,perphone=per)
             user.save()
             return redirect('/register_success_page')
    return render(request,'register_success.html')

# 注册成功跳转的页面
def fun_register_success_page(request):
    return render(request,'register_success.html')